﻿using DataSync.Common;
using log4net;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Boco.CommonLib;

namespace DataSync.Proc
{
    class DataCollectBase : TaskBase
    {
        private static ILog log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        private IDataSyncReader reader; //数据输入
        private IDataSyncWriter writer; //数据输出

        public DataCollectBase(TaskConf conf) : base(conf)
        {

        }

        public override void Init()
        {
            var config = TaskConfig.GetTaskConfig(this.CurTaskConfig.Id);
            //配置读取
            var readerConf = config.Element("Reader");
            var writerConf = config.Element("Writer");

            var readerType = readerConf.GetAttribute("Type");
            var writerType = writerConf.GetAttribute("Type");

            if (string.IsNullOrEmpty(readerType) || string.IsNullOrEmpty(writerType))
            {
                throw new ApplicationException(string.Format("任务{0}配置不正确", CurTaskConfig.Name));
            }

            //初始化 实例
            reader = InterfaceFactory.GetReader(readerType);
            if (reader == null)
            {
                throw new ApplicationException(string.Format("任务{0}配置不正确：未实现的reader类型:{1}", CurTaskConfig.Name, readerType));
            }
            writer = InterfaceFactory.GetWriter(writerType);
            if (writer == null)
            {
                throw new ApplicationException(string.Format("任务{0}配置不正确：未实现的writer类型:{1}", CurTaskConfig.Name, writerType));
            }

            reader.Init(readerConf, writer);
            writer.Init(writerConf);

            log.InfoFormat("任务{0}初始化成功", CurTaskConfig.Name);
        }

        public override void Run()
        {
            log.DebugFormat("任务{0}处理开始", CurTaskConfig.Name);
            int successNum = 0;
            try
            {
                successNum = reader.StartRead();
            }
            finally
            {
                writer.Close();
                reader.Close();
            }

            log.DebugFormat("任务{0}处理完成,本次成功处理:{1}", CurTaskConfig.Name, successNum);
        }
    }
}
